package com.yylending.las.lending.process.confirmloan;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.tbruyelle.rxpermissions.Permission;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yylending.las.Global;
import com.yylending.las.R;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.Constants;
import com.yylending.las.common.dialog.RepaymentScheduleDialog;
import com.yylending.las.common.location.LocationPresenter;
import com.yylending.las.common.location.entity.Location;
import com.yylending.las.common.utils.FormatUtils;
import com.yylending.las.StatIDSet;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.common.utils.PermissionUtil;
import com.yylending.las.common.widgets.CommonDialog;
import com.yylending.las.lending.process.ProcessActivity;
import com.yylending.las.lending.quota.idcard.IdCardModel;
import com.yylending.las.personal.bandcard.BoundBankCards;
import com.yylending.las.webview.WebViewActivity;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

public class ConfirmLoanFragment extends BaseFragment implements ConfirmLoanPresenter.View, LocationPresenter.View, CompoundButton.OnCheckedChangeListener {

	private static final String TAG = ConfirmLoanFragment.class.getSimpleName();

	private static final int REQUEST_CODE_GPS = 100;
	public static final int LOADER_ID_CONFIRM_LOAN = 202;
	public static final int LOADER_ID_LOCATE = 203;
	@BindView(R.id.proposer_tv)
	TextView mProposerTv;
	@BindView(R.id.identity_card_tv)
	TextView mIdentityCardTv;
	@BindView(R.id.applied_amount_tv)
	TextView mAppliedAmountTv;
	//@BindView(R.id.arrival_amount_tv)
	//TextView mArrivalAmountTv;
	@BindView(R.id.periods_tv)
	TextView mPeriodsTv;
	@BindView(R.id.terminally_repayment_tv)
	TextView mTerminallyRepaymentTv;
	@BindView(R.id.first_pay_date_tv)
	TextView mFirstPayDateTv;
	@BindView(R.id.due_bank_name_tv)
	TextView mDueBankNameTv;
	@BindView(R.id.month_repay_date_tv)
	TextView mMonthRepayDateTv;
	@BindView(R.id.chk)
	CheckBox mChk;
	@BindView(R.id.submit_btn)
	Button mSubmitBtn;
	@BindView(R.id.due_bank_tail_number_tv)
	TextView mDueBankTailNumberTv;

	/** 还款计划 */
	private Dialog mDialog;
	/** 每月应还 */
	private String mTerminallyRepayment;
	/** 首次还款日 */
	private String mFirstPayDate;
	/** 定位信息 */
	private Location mLocation;
	/** 是否需要在定位成功之后自动提交 */
	private boolean mAutoCommit;

	private LocationPresenter mLocatePresenter;
	private ConfirmLoanPresenter mConfirmLoanPresenter;
	Unbinder mUnbind;

	public static BaseFragment newInstance() {
		BaseFragment fragment = new ConfirmLoanFragment();
		return fragment;
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_confirm_loan, null);
		mUnbind = ButterKnife.bind(this, view);
		return view;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		EventAgent.register(this);
		mChk.setOnCheckedChangeListener(this);
		setAmount();
		Intent intent = getActivity().getIntent();
		List<BoundBankCards.BankInfo> bankInfos = intent.getParcelableArrayListExtra(ProcessActivity.BANK_INFO);
		BoundBankCards.BankInfo bankInfo = bankInfos.get(0);
		mDueBankNameTv.setText(bankInfo.getBankName());
		String format = String.format(getString(R.string.bank_tail_number), bankInfo.getNumber().substring(bankInfo.getNumber().length() - 4));
		mDueBankTailNumberTv.setText(format);
	}

	/**
	 * 更新借款金额、期数、每期应还、到账金额的UI
	 */
	private void setAmount() {
		mAppliedAmountTv.setText(FormatUtils.getAmountWithSymbol(ProcessActivity.mProcess.businessSum));
		mPeriodsTv.setText(String.format(getString(R.string.loan_term), ProcessActivity.mProcess.loanTerm));
		//mArrivalAmountTv.setText(ProcessActivity.mProcess.amountActualToAccount);
		mTerminallyRepayment = ProcessActivity.mProcess.terminallyRepayment;
		mTerminallyRepaymentTv.setText(mTerminallyRepayment);
	}

	public static class ConfirmLoadBean {
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void changeAmount(ConfirmLoanFragment.ConfirmLoadBean bean) {
		setAmount();
	}

	@Override
	public void onStart() {
		super.onStart();
		Global.setThirdPartyPageOpenedFlag(false);
		mAutoCommit = false;
		getActivity().getSupportLoaderManager().initLoader(LOADER_ID_CONFIRM_LOAN, null, this);
		getActivity().getSupportLoaderManager().initLoader(LOADER_ID_LOCATE, null, this);
		mFirstPayDate = getChangedBeginDate();
		mFirstPayDateTv.setText(mFirstPayDate);
		String firstPayDate = String.format(getString(R.string.first_pay_date_content), mFirstPayDate.split("/")[2]);
		mMonthRepayDateTv.setText(firstPayDate);
	}

	/**
	 * 每月1-28号放款，还款日为次月对应日
	 * 每月29、30、31日放款，还款日为次月26、27、27日
	 *
	 * @return 首次还款日
	 */
	private String getChangedBeginDate() {
		long realTime = com.yyfax.infrastructure.Constants.getRealTime();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
		String changedBeginDate = dateFormat.format(realTime);
		String[] dates = changedBeginDate.split("/");
		int year = Integer.valueOf(dates[0]);
		int month = Integer.valueOf(dates[1]);
		month += 1;
		if (month > 12) {
			month -= 12;
			year += 1;
		}
		String monthStr = String.valueOf(month);
		if (1 == monthStr.length()) {
			monthStr = "0" + monthStr;
		}
		String day = dates[2];
		if (day.compareTo("29") >= 0) {
			HashMap<String, String> dayChangedHashMap = new HashMap();
			dayChangedHashMap.put("29", "26");
			dayChangedHashMap.put("30", "27");
			dayChangedHashMap.put("31", "27");
			day = dayChangedHashMap.get(day);
		}
		return "" + year + "/" + monthStr + "/" + day;
	}


	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mUnbind.unbind();
		EventAgent.unregister(this);
		getActivity().getSupportLoaderManager().destroyLoader(LOADER_ID_CONFIRM_LOAN);
		getActivity().getSupportLoaderManager().destroyLoader(LOADER_ID_LOCATE);
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_CONFIRM_LOAN:
				if (null == mConfirmLoanPresenter) {
					mConfirmLoanPresenter = (ConfirmLoanPresenter) data;
					mConfirmLoanPresenter.attach(this);
					mConfirmLoanPresenter.getIdCard(Constants.CUSTOMER_TYPE_IDENTITY);
				}
				break;
			case LOADER_ID_LOCATE:
				mLocatePresenter = (LocationPresenter) data;
				mLocatePresenter.attach(this);
				PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
				break;
		}

	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_CONFIRM_LOAN:
				return new PresenterLoader<>(getActivity(), new ConfirmLoanPresenter.Generator());
			case LOADER_ID_LOCATE:
				return new PresenterLoader<>(getActivity(), new LocationPresenter.Generator());
		}
		return null;
	}

	@OnClick({R.id.terminally_repayment_tv, R.id.read_repayment_schedule_btn, R.id.submit_btn, R.id.read_legal_documents_btn})
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.terminally_repayment_tv:
				showOneBtnDialog(R.string.pay_date_explain);
				break;
			case R.id.read_repayment_schedule_btn:
				mDialog = new RepaymentScheduleDialog(getActivity(), Integer.valueOf(ProcessActivity.mProcess.loanTerm),
						mTerminallyRepayment, mFirstPayDate); //实时初始化，确保获取的数据是最新的
				mDialog.show();
				StatService.onEvent(getContext(), StatIDSet.EVENT_ID_VIEW_REPAYMENT_PLAN_1);
				break;
			case R.id.read_legal_documents_btn:
				StatService.onEvent(getContext(), StatIDSet.EVENT_ID_VIEW_LEGAL_FILE_2);
				WebViewActivity.start(getActivity(), Global.BASE_URL + Global.LEGAL_DOCUMENT_URL, getString(R.string.legal_document), -1);
				break;
			case R.id.submit_btn:
				StatService.onEvent(getActivity(), StatIDSet.EVENT_ID_CONFIRM_SUBMIT_BORROW_MONEY);
				mSubmitBtn.setEnabled(false);
				if(null == mLocation){
					mAutoCommit = true;
					PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
				}else{
					mAutoCommit = false;
					showLoading(false);
					confirmLoan();
				}
				break;
		}
	}

	/**
	 * 提交借款
	 */
	private void confirmLoan(){
		mConfirmLoanPresenter.confirmLoan(ProcessActivity.mProcess.loanTerm, ProcessActivity.mProcess.realBusinessSum, String.valueOf(mLocation.longitude), String.valueOf(mLocation.latitude), Constants.LOAN_ONLINE);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			mSubmitBtn.setEnabled(true);
			StatService.onEventWithSingleAttribute(getContext(), StatIDSet.EVENT_ID_CHECKED_LEGAL_DOCUMENTS_2, StatService.ATTRIBUTE_VALUE_ONE);
		} else {
			mSubmitBtn.setEnabled(false);
			StatService.onEventWithSingleAttribute(getContext(), StatIDSet.EVENT_ID_CHECKED_LEGAL_DOCUMENTS_2, StatService.ATTRIBUTE_VALUE_TWO);
		}
	}

	@Override
	public void confirmLoanSuccess(ConfirmLoanModel.ConfirmLoan confirmLoan) {
		mSubmitBtn.setEnabled(true);
		ProcessActivity.mStatus = confirmLoan.loanState;
		((ProcessActivity) getActivity()).showResult();
	}

	@Override
	public void confirmLoanFailure(String tips) {
		mSubmitBtn.setEnabled(true);
		showToast(tips);
	}

	@Override
	public void confirmLoanRepeat(String tips) {
		showToast(tips);
		getActivity().finish();
	}

	@Override
	public void creditReportingOutdated() {
		showToast(R.string.credit_report_outdated);
		getActivity().finish();
	}

	@Override
	public void getIdCardSuccess(IdCardModel.IdCard idCard) {
		mProposerTv.setText(idCard.iname);
		mIdentityCardTv.setText(FormatUtils.hiddenPartStr(6, 14, "*", idCard.inumber));
	}

	@Override
	public void getIdCardFailure(String tips) {
		showToast(tips);
	}


	public boolean dismiss() {
		boolean isShowing = false;
		if (mDialog != null && mDialog.isShowing()) {
			isShowing = true;
			mDialog.dismiss();
		}
		return isShowing;
	}

	@Override
	public void onFunctionalCompleted(boolean autoTips) {
		super.onFunctionalCompleted(autoTips);
		dismissLoading();
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, final int functionalCode) {
		super.onFunctionalError(e, autoTips, functionalCode);
		getActivity().runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if(functionalCode==ConfirmLoanModel.METHOD_CONFIRM_LOAN) {
					mSubmitBtn.setEnabled(true);
				}
			}
		});
	}

	@Override
	public void onLocateSuccess(Location location) {
		mLocation = location;
		if(mAutoCommit) confirmLoan();
	}

	@Override
	public void onLocateFail(boolean noPermission) {
		if(mAutoCommit){
			dismissLoading();
			mAutoCommit = false;
			mSubmitBtn.setEnabled(true);
		}
		if (noPermission) {
			showNeedLocationPermission();
		} else {
			if (com.yyfax.infrastructure.Constants.isConnected) {
				if(PermissionUtil.isGpsOPen(getActivity())){
					if(PermissionUtil.isSdkUnderM()){
						showNeedLocationPermission();
					}else{
						showToast(R.string.locate_need_retry);
					}
				}else{
					showTwoBtnDialog(R.string.gps_permission_hint, R.string.go_to_settings, R.string.cancel, new CommonDialog.ButtonClickListener() {
						@Override
						public void onCancel(CommonDialog dialog) {
							dialog.dismiss();
						}

						@Override
						public void onConfirm(CommonDialog dialog) {
							//忽略手势密码
							Global.setThirdPartyPageOpenedFlag(true);
							//跳转GPS设置界面
							Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							startActivityForResult(intent, REQUEST_CODE_GPS);
							dialog.dismiss();
						}
					}, true);
				}
			} else {
				showToast(R.string.locate_error_due_to_network);
			}
		}
	}

	@Override
	public void showDialog() {

	}

	@Override
	public void dismissDialog() {

	}

	private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			switch (permission.name) {
				case Manifest.permission.ACCESS_COARSE_LOCATION:
					if (permission.granted) {
						if(mAutoCommit){
							showLoading(false);
						}
						mLocatePresenter.startLocation(false);
					} else {
						if(mAutoCommit){
							dismissLoading();
						}
						showNeedLocationPermission();
					}
					break;
				default:
					break;
			}

		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {

		}
	};

	private void showNeedLocationPermission(){
		showTwoBtnDialog(getString(R.string.location_permission_hint, getString(R.string.app_name)), getString(R.string.go_to_settings), getString(R.string.cancel), new CommonDialog.ButtonClickListener() {
			@Override
			public void onCancel(CommonDialog dialog) {
				dialog.dismiss();
			}

			@Override
			public void onConfirm(CommonDialog dialog) {
				//忽略手势密码
				com.yylending.las.Global.setThirdPartyPageOpenedFlag(true);
				Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
				startActivity(intent);
				dialog.dismiss();
			}
		}, true);
	}
}